#include "TCP.h"

static int server_fd = -1;
static struct sockaddr_in server_addr, client_addr;

int TCP_Sercer_Config(int port, const char *ip) {
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        perror("socket error");
        return -1;
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = (ip == NULL) ? INADDR_ANY : inet_addr(ip);

    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind error");
        close(server_fd);
        return -1;
    }

    if (listen(server_fd, 5) < 0) {
        perror("listen error");
        close(server_fd);
        return -1;
    }
    return server_fd;
}

int TCP_Accept() {
    socklen_t client_len = sizeof(client_addr);
    int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
    if (client_fd < 0) {
        perror("accept error");
    }
    return client_fd;
}